package com.simplecontact.activities;

import java.util.Date;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

import com.simplecontact.R;
import com.simplecontact.classes.Calendar;
import com.simplecontact.classes.CalendarBundle;
import com.simplecontact.utils.Utils;

public class ActCreateCalendar extends Activity {
	
	CalendarBundle cb = null;
	private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;
	EditText edContent;
	EditText edUrlMusic;	
	EditText edDate;
	EditText edTime;
	Button btnUrlMusic;
	Button btnDone;
	Button btnRevert;
	private String strUrlMusic;
	
	public ContentValues prepareToInsert(){
		ContentValues values = new ContentValues();
		String s = new Date(mYear - 1900, mMonth, mDay, mHour, mMinute).toGMTString();
		long v =  Date.parse(s);
		values.put(Calendar.CalendarColumns.DATETIME, v);
		values.put(Calendar.CalendarColumns.CONTENT, edContent.getText().toString());		
		if(strUrlMusic=="")values.put(Calendar.CalendarColumns.URLMUSIC, "");
		else values.put(Calendar.CalendarColumns.URLMUSIC, strUrlMusic);		
		return values;
	}
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_calendar);
        edContent = (EditText)findViewById(R.id.edContent);
        
        edUrlMusic = (EditText)findViewById(R.id.edUrlMusic);
        btnDone = (Button)findViewById(R.id.btnDone);
        btnDone.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(cb==null)getContentResolver().insert(Calendar.CalendarColumns.CONTENT_URI, prepareToInsert());
    			else getContentResolver().update(Calendar.CalendarColumns.CONTENT_URI, prepareToInsert(), "_id=" + cb.getId(), null);
    			finish();
			}
		});
        
        btnRevert = (Button)findViewById(R.id.btnRevert);
        btnRevert.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
        
        edDate = (EditText)findViewById(R.id.edDate);
        edDate.setOnClickListener(new OnClickListener() {
        	@Override
			public void onClick(View v) {
        		showDialog(Utils.DATE_DIALOG_ID);
        	}
        });
        edTime = (EditText)findViewById(R.id.edTime);
        edTime.setOnClickListener(new OnClickListener() {
        	@Override
			public void onClick(View v) {
        		showDialog(Utils.TIME_DIALOG_ID);
        	}
        });
        btnUrlMusic = (Button)findViewById(R.id.btnUrlMusic);
        btnUrlMusic.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
	            intent.setType("music/*");
	            intent.setAction(Intent.ACTION_GET_CONTENT);
	            startActivityForResult(Intent.createChooser(intent, "Select Music"), Utils.CAPTURE_MUSIC);				
			}
		});
        cb = getIntent().getParcelableExtra("calendarbundle");        
        if(cb!=null){
        	edContent.setText(cb.getContent());
        	edUrlMusic.setText(cb.getUrlMusic());
        	Date date = new Date(cb.getDateTime());        	        	                	        	
        	
        	mYear = date.getYear() + 1900;
	        mMonth = date.getMonth() + 1;
	        mDay = date.getDate();
	        mHour = date.getHours();
	        mMinute = date.getMinutes();
	        updateDisplay();
        }
        else{
	        final java.util.Calendar cd = java.util.Calendar.getInstance();
	        mYear = cd.get(java.util.Calendar.YEAR);
	        mMonth = cd.get(java.util.Calendar.MONTH);
	        mDay = cd.get(java.util.Calendar.DAY_OF_MONTH);        
	        mHour = cd.get(java.util.Calendar.HOUR_OF_DAY);
	        mMinute = cd.get(java.util.Calendar.MINUTE);
	        updateDisplay();
        }
    }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Utils.CAPTURE_MUSIC) {
            if (resultCode == RESULT_OK) {
            	//Save image to PictureAnswer object
            	if(data!=null){
            		Uri selectedImageUri = data.getData();
                    //OI FILE Manager
                    String filemanagerstring = selectedImageUri.getPath();
                    if(filemanagerstring!="")
                    	btnUrlMusic.setText(filemanagerstring);
            	}
            }
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {      
    	menu.add(0, Utils.MENU_DONE, 0, getString(R.string.strDone)).setIcon(R.drawable.update);
    	menu.add(0, Utils.MENU_REVERT, 0,getString(R.string.strRevert)).setIcon(R.drawable.cancel);
    	return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {    
    	// Handle item selection    
    	switch (item.getItemId()) {  
    		case Utils.MENU_DONE:
    			if(cb==null)getContentResolver().insert(Calendar.CalendarColumns.CONTENT_URI, prepareToInsert());
    			else getContentResolver().update(Calendar.CalendarColumns.CONTENT_URI, prepareToInsert(), "_id=" + cb.getId(), null);
    			finish();
    			break;
    		case Utils.MENU_REVERT:
    			finish();
    			break;               		
    	}    	
    	return super.onOptionsItemSelected(item);
    }
    
    private void updateDisplay() {
    	edDate.setText(mYear + "/" + mMonth + "/" + mDay);
    	edTime.setText(mHour + ":" + mMinute);
    }
    
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {     
            case Utils.DATE_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(mYear, mMonth - 1, mDay);
                break;
            case Utils.TIME_DIALOG_ID:
                ((TimePickerDialog) dialog).updateTime(mHour, mMinute);
                break;    
        }
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case Utils.DATE_DIALOG_ID:
                return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
            case Utils.TIME_DIALOG_ID:
                return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, true);    
        }
        return null;
    }
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
    	@Override
        	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    			mHour = hourOfDay;
    			mMinute = minute; 
    			updateDisplay();
        }
    };      
    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear+1;
                mDay = dayOfMonth;
                updateDisplay();
            }
        };   
}
